<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账号状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="账号状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['permissions:user:add']"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['permissions:user:add']"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="roleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="手机号码" prop="phonenumber" width="150" />
      <el-table-column
        label="姓名"
        prop="userName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="分配角色"
        :show-overflow-tooltip="true"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.roleName != null ? scope.row.roleName : "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updateBy != "" ? scope.row.updateBy : "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" width="180">
        <template slot-scope="scope">
          <span>{{
            scope.row.updateTime != null ? parseTime(scope.row.updateTime) : "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ scope.row.status == 0 ? "正常" : "停用" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['permissions:user:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleStatusChange(scope.row)"
            v-hasPermi="['permissions:user:disabled']"
            >{{ scope.row.status != "0" ? "启用" : "停用" }}</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleResetPass(scope.row)"
            v-hasPermi="['permissions:user:resetPass']"
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item
          label="登录密码"
          prop="password"
          v-if="title != '修改用户'"
        >
          <el-input
            v-model="form.password"
            placeholder="限5-12个字，只能输入字母、数字"
            max="12"
            min="5"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="form.phonenumber"
            placeholder="请输入手机号码"
            max="20"
          />
        </el-form-item>
        <el-form-item label="选择角色">
          <el-checkbox-group v-model="formRole">
            <el-checkbox
              v-for="(item, index) in NLS"
              :key="index"
              :label="item.roleId"
              >{{ item.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配用户数据权限对话框 -->
    <el-dialog
      title="重置密码"
      :visible.sync="openDataScope"
      width="500px"
      append-to-body
    >
      <el-form ref="form2" :model="form2" :rules="rules2" label-width="100px">
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="form2.password"
            placeholder="限5-12个字，只能输入字母、数字"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDataScope">确认提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  getUser,
} from "@/api/system/user";
import { listRole } from "@/api/system/role";
export default {
  name: "user",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      NLS: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        phonenumber: undefined,
        userName: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单校验
      rules: {
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
            required: true,
          },
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
          {
            pattern: /^[^<>"'|\\]+$/,
            message: "不能包含非法字符：< > \" ' \\ |",
            trigger: "blur",
          },
        ],
        userName: [
          {
            required: true,
            message: "用户名称输入有误，请检查",
            trigger: "blur",
          },
        ],
      },
      formRole: [],
      form2: {},
      rules2: {
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
          {
            pattern: /^[^<>"'|\\]+$/,
            message: "不能包含非法字符：< > \" ' \\ |",
            trigger: "blur",
          },
        ],
      },
      userInfo: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.roleList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 打开重置密码
    handleResetPass(c) {
      this.userInfo = c;
      this.openDataScope = true;
      this.form2 = {
        password: "",
      };
      this.resetForm("form2");
    },
    // 重置密码确认
    cancelDataScope() {
      this.$refs["form2"].validate((valid) => {
        if (valid) {
          resetUserPwd(this.userInfo.userId, this.form2.password).then(
            (response) => {
              this.$modal.msgSuccess(
                "修改成功，新密码是：" + this.form2.password
              );
              this.openDataScope = false;
              this.getList();
            }
          );
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        roleIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status != "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
        .then(function () {
          return changeUserStatus(row.userId, row.status === "0" ? "1" : "0");
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
          this.getList();
        });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
      this.formRole = [];
      getUser().then((response) => {
        this.NLS = response.roles;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "修改用户";
      this.open = true;
      this.form = JSON.parse(JSON.stringify(row));
      const userId = row.userId || this.ids;
      getUser(userId).then((response) => {
        console.log(response);
        this.NLS = response.roles;
        this.formRole = response.roleIds;
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.formRole.length < 1) {
            this.$modal.msgWarning("用户至少选择一个");
            return false;
          }
          this.form.roleIds = this.formRole;
          if (this.form.userId != undefined) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.userId || this.ids;
      this.$modal
        .confirm('是否确认删除用户编号为"' + roleIds + '"的数据项？')
        .then(function () {
          return delUser(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
